package com.amado.course34Thread.job;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 使用两个线程做龟兔赛跑（同时起跑），跑20米:
 乌龟：速度4m/s，不休息
 兔子：速度5m/s,每跑10米休息2
 谁先跑完
 */
public class TortoiseRabbitThread {
	static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static void main(String[] args) {
        Tortoise tortoise = new Tortoise(4,20);
        new Thread(tortoise,"乌龟").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                //动物速度
                int speed = 5;
                //当前已经跑的路程
                int now =0;
                //总路径
                int mileage=20;
                long beginTime = new Date().getTime();
                while(now<mileage){
                    System.out.println(Thread.currentThread().getName()+simpleDateFormat.format(new Date())+"跑了"+now);
                    if(now>0 && now%10==0){
                        try {
                        	System.out.println(Thread.currentThread().getName()+"开始休息");
                            Thread.sleep(2000);
                            System.out.println(Thread.currentThread().getName()+"结束休息，开始跑");
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    now +=speed;
                }
                long endTime = new Date().getTime();
                System.out.println(Thread.currentThread().getName()+"跑完了。。。。"+(endTime-beginTime)/1000+"秒");
            }
        },"兔子").start();
    }
    static class Tortoise extends Thread{
        //动物速度
        protected int speed;
        //当前已经跑的路程
        protected int now;
        //总路径
        protected int mileage;
        /**
         *
         * @param speed 速度
         * @param mileage 里程
         */
        Tortoise(int speed,int mileage){
            this.speed= speed;
            this.mileage=mileage;
        }

//        @Override
//        public void run() {
//            while(now<mileage){
//                System.out.println(Thread.currentThread().getName()+simpleDateFormat.format(new Date())+"跑了"+now);
//                now +=speed;
//                try {
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//            System.out.println(Thread.currentThread().getName()+"跑完了。。。。");
//        }
    }
}


